/**
 * 题目描述：
    要求1:
    点击当前title将title的值置为'active'文本

    要求2:
    监听回车键，打印最新的list信息，console, alert都行 （禁止改变useEffect 依赖项）

    要求3
    如果list中title都拆出来变成四个固定的模块(布局任意，不要求)
    每个模块点击的时候有500ms的loading状态，且有50%的几率会err,
    如何维护hooks，给出较好的设计方案
 */

import React, { useEffect, useState } from "react";
import { useRef } from "react";
import { useCallback } from "react";

const Home = () => {
  const [list, setList] = useState([
    { module: [{ title: "A" }, { title: "B" }] },
    { module: [{ title: "C" }, { title: "D" }] },
  ]);
  const listRef = useRef(null);

  listRef.current = list;

  useEffect(() => {
    // 按下回车时 打印出最新的list信息
    const listenerCallback = () => {
      console.log(JSON.stringify(listRef.current));
    };
    document.addEventListener("keydown", listenerCallback);

    return () => {
      document.removeEventListener("keydown", listenerCallback);
      listRef.current = null;
    };
  }, []);

  const handleTitleClick = useCallback(
    (moduleItem, title) => {
      const newList = [...list];
      const findModule = list.find((module) => module === moduleItem);

      if (findModule) {
        const findTitleItem = findModule.module.find((titleItem) => titleItem.title === title);
        console.log(findTitleItem);

        if (findTitleItem) {
          findTitleItem.title = "active";
        }
      }
      setList(newList);
    },
    [list, setList]
  );

  return (
    <div
      style={{
        position: "relative",
        left: "30px",
        width: "300px",
        height: "300px",
        border: "1px solid #000",
      }}
    >
      {list.map((moduleItem) => {
        return (
          <div
            style={{
              display: "flex",
              marginLeft: "48px",
              fontSize: "30px",
            }}
          >
            {moduleItem.module.map((titleItem) => {
              return (
                <div
                  style={{
                    marginLeft: "20px",
                    marginTop: "20px",
                  }}
                  onClick={() => handleTitleClick(moduleItem, titleItem.title)}
                >
                  {titleItem.title}
                </div>
              );
            })}
          </div>
        );
      })}
    </div>
  );
};

export default Home;
